<?php
ob_start();
function sentimentFromTweets($mid)  //bunları sağla sentiment döndürsün
{
	//db connection
	$con = mysql_connect('localhost','root','');
	mysql_select_db('sentana', $con);
	$sql = 	"SELECT EID FROM entities WHERE MID='".$mid."'";
	$result = mysql_query($sql, $con) or die(mysql_error());
	
	while($row = mysql_fetch_array($result))   //aslında döngüye gerek yok sadece 1 tane dönecek ama öbür metodla saçmaladı
	{	
		$eid=$row['EID'];
	}
	
	$sql="SELECT TID FROM tweet2entities WHERE EID='".$eid."'";
	$result = mysql_query($sql,$con);
 
    $positive=0;
    $negative=0;

    $sql="SELECT count(*) As PosCount FROM tweet2entities WHERE EID='".$eid."' AND Sentiment='1'";
    $result = mysql_query($sql,$con);
    if( $row = mysql_fetch_array($result))
    	$positive = $row["PosCount"];


    $sql="SELECT count(*) As NegCount FROM tweet2entities WHERE EID='".$eid."' AND Sentiment='-1'";
    $result = mysql_query($sql,$con);
    if( $row = mysql_fetch_array($result))
    	$negative = $row["NegCount"];
	
	$arr[0]=$positive;
	$arr[1]=$negative;
	echo $positive;
	echo $negative;
	echo "burdafonskionda";
	return $arr;
}
function sentimentFromHash($hash)  //bunları sağla sentiment döndürsün
{
	//db connection
	$con = mysql_connect('localhost','root','');
	mysql_select_db('sentana', $con);
	
	$sql="SELECT TID FROM tweet2hashtags WHERE Hash='".$hash."'";
	$result = mysql_query($sql,$con);
 
    $positive=0;
    $negative=0;

    $sql="SELECT count(*) As PosCount FROM tweet2hashtags WHERE Hash='".$hash."' AND Sentiment='1'";
    $result = mysql_query($sql,$con);
    if( $row = mysql_fetch_array($result))
    	$positive = $row["PosCount"];


    $sql="SELECT count(*) As NegCount FROM tweet2hashtags WHERE Hash='".$hash."' AND Sentiment='-1'";
    $result = mysql_query($sql,$con);
    if( $row = mysql_fetch_array($result))
    	$negative = $row["NegCount"];
	
	$arr[0]=$positive;
	$arr[1]=$negative;
	echo $positive;
	echo $negative;
	echo "burdafonskionda";
	return $arr;
}
function produceHorizontalGraph($positive,$negative,$index)  //şimdilik positif ve negatif dönecek
{
	//grafiği çizer

	$data1=array($positive);
	$data2=array($negative);
	
	$graph = new Graph(200,37,'auto');
	$graph->SetScale("textlin");
	$theme_class=new UniversalTheme;
	$graph->SetTheme($theme_class);
	$graph->Set90AndMargin(0,0,0,0);
	$graph->SetMarginColor("black");
	$graph->img->SetAngle(90); 
	$graph->xaxis->SetTickLabels(' ');
	$graph->xaxis->SetColor("black","black");
	$graph->SetBox(false);
	$graph->ygrid->Show(false);
	$graph->ygrid->SetFill(false);
	$graph->yaxis->HideLine(true);
	$graph->yaxis->HideTicks(true,true);
	
	$b1plot = new BarPlot($data1);
	$b2plot = new BarPlot($data2);	
	$b1plot->SetWeight(0);
	$b1plot->SetWidth(37);	
	$b1plot->SetColor("green");
	$b1plot->SetFillColor("green");
	$b2plot->SetWeight(0);
	$b2plot->SetWidth(37);
	$b2plot->SetColor("red");
	$b2plot->SetFillColor("red");
	
	$gbbplot = new AccBarPlot(array($b1plot,$b2plot));
	
	$graph->Add($gbbplot);
	$graph->SetBackgroundImage("design_files/black.png",BGIMG_FILLFRAME);
	
	$graph->SetBackgroundImage("design_files/black.png",BGIMG_FILLFRAME);
	@unlink("reports/".$_SESSION['userId']."r".$index.".png"); 
	$graph->Stroke("reports/".$_SESSION['userId']."r".$index.".png");
	
}

ob_end_flush(); 
?>

<?php

date_default_timezone_set('Europe/Istanbul');
ob_start();
function getTypeFromId()
{
	$jsonquerystr = "http://www.freebase.com/api/service/mqlread?query={%20%22extended%22:1%2C%20%22query%22%3A%20{%20%22id%22:%20%22".$_SESSION['idOfKeyword']."%22%2C%20%22type%22:%20%22/common/topic%22%2C%20%22notable_for%22:%20null%20}%20}";
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL,$jsonquerystr);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,10);
	$jsonresultstr = curl_exec($ch);
	curl_close($ch); 
	$resultarray = json_decode($jsonresultstr, true);
	$notableFor = $resultarray["result"]["notable_for"]; //string düzgün gelsin / olmadan sadece type
	list($t1,$t2,$notableFor) = split('/', $notableFor);
	$str=str_replace('_',' ',$notableFor,$cnt);
	$_SESSION['keywordType']=strtoupper($str);
}
function getTypeFromMid()
{
	$jsonquerystr = "http://www.freebase.com/api/service/mqlread?query={%20%22extended%22:1%2C%20%22query%22%3A%20{%20%22mid%22:%20%22".$_SESSION['keywordMid']."%22%2C%20%22type%22:%20%22/common/topic%22%2C%20%22notable_for%22:%20null%20}%20}";
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL,$jsonquerystr);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,10);
	$jsonresultstr = curl_exec($ch);
	curl_close($ch); 
	$resultarray = json_decode($jsonresultstr, true);
	$notableFor = $resultarray["result"]["notable_for"]; //string düzgün gelsin / olmadan sadece type
	list($t1,$t2,$notableFor) = split('/', $notableFor);
	$str=str_replace('_',' ',$notableFor,$cnt);
	$_SESSION['keywordType']=strtoupper($str);
}
function getMidFromId()
{
	$jsonquerystr = "http://www.freebase.com/api/service/mqlread?query={%20%22extended%22:1%2C%20%22query%22%3A%20{%20%22id%22:%20%22".$_SESSION['idOfKeyword']."%22%2C%20%22type%22:%20%22/common/topic%22%2C%20%22mid%22:%20null%20}%20}";
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL,$jsonquerystr);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,30);
	$jsonresultstr = curl_exec($ch);
	curl_close($ch); 
	$resultarray = json_decode($jsonresultstr, true);
	
	$str = $resultarray["result"]["mid"]; //string düzgün gelsin / olmadan sadece type
	$_SESSION['keywordMid']=$str;

}
ob_end_flush(); 
?>

<?php //rapor sonucunda çıkacak bütün grafikler burda üretiliyor
session_start();
ob_start();
$dir = 'reports'; //bütün grafikler bu klasörün içinde olacak
if(!file_exists($dir)) 
{
 mkdir ($dir, 0777);
}

//db connection
$con = mysql_connect('localhost','root','');
mysql_select_db('sentana', $con);
$_SESSION['keywordMid']="";
$_SESSION['hashTag']="";
$_SESSION['txtSearch']="";
$_SESSION['idOfKeyword']="";
 $_SESSION['keywordType']="";
if( ISSET($_POST['txtSearch']) )
{
        $_SESSION['idOfKeyword']=$_POST['idOfKeyword'];
        $_SESSION['txtSearch']=$_POST['txtSearch'];
		if($_SESSION['txtSearch'][0]=='#')
		{
			$_SESSION['hashTag']=1;
			$_SESSION['keywordType']="HASHTAG";
		}
		else
		{
			getTypeFromId();
			getMidFromId();
		//	echo $_SESSION['idOfKeyword'];
			//echo $_SESSION['keywordType'];
			echo "burada1";
			echo "mid:".$_SESSION['keywordMid'];
			echo "burada2";
		}
      
}
else  //indexteki populer graph linklerden geliyor
{
	$_SESSION['txtSearch']=$_GET['txtSearch'];
	$_SESSION['keywordType']=$_GET['keywordType'];
	$_SESSION['keywordMid']=$_GET['mid'];
	getTypeFromMid();
}
require_once ('design_files/graph_src/jpgraph.php');
require_once ('design_files/graph_src/jpgraph_pie.php');
require_once ('design_files/graph_src/jpgraph_pie3d.php');
require_once ('design_files/graph_src/jpgraph_bar.php');
require_once ('design_files/graph_src/jpgraph_line.php');


echo $_SESSION['txtSearch'];
//search ettiğin keywordün entity idsiyle aynı olan bütün tweetlerin sentimentini al
if($_SESSION['hashTag']==1)
{
	$arr=sentimentFromHash($_SESSION['txtSearch']);
}
else
{
	$arr=sentimentFromTweets($_SESSION['keywordMid']);
}

$positive=$arr[0];
$negative=$arr[1];
//pie chart başlangıç
if($positive+$negative>0)
{
	$data = array($positive,$negative); //pie chart için data burda 
	
	$graph = new PieGraph(600,350);
	$graph->SetShadow();
	
	$graph->title->Set("General feeling for ". $_SESSION['txtSearch']);
	$graph->title->SetFont(FF_VERDANA,FS_BOLD,13); 
	$graph->title->SetColor("black");
	$graph->legend->Pos(0.0,0.9);
	$graph->SetColor("black");
	//$graph->SetBackgroundImage("design_files/black.png",BGIMG_FILLFRAME);
	$p1 = new PiePlot3d($data);
	$p1->SetTheme("sand");
	$p1->SetCenter(0.5);
	$p1->SetAngle(60);
	$p1->value->SetFont(FF_ARIAL,FS_NORMAL,12);
	$p1->value->SetColor("black");
	$p1->SetLegends(array("Happy :)","Sad :("));
	
	$graph->Add($p1);
	@unlink($dir . "/" . $_SESSION['userId'] . "g1.png"); 
	$graph->Stroke($dir . "/" . $_SESSION['userId'] . "g1.png");
	$_SESSION['sentimentAvailable']=1;
}
else
{
	$_SESSION['sentimentAvailable']=0;
	@unlink($dir . "/" . $_SESSION['userId'] . "g1.png"); 
}
$_SESSION['positive']=$positive;
$_SESSION['negative']=$negative;
//pie chart bitti

//weekly sentiment graph başla
//weekly sentiment o keyword için

$graph = new Graph(750,320,'auto');
$graph->SetScale("textlin");
$graph->SetY2Scale("lin",0,100);
$graph->SetY2OrderBack(false);
$theme_class = new UniversalTheme;
$graph->SetTheme($theme_class);
$graph->SetColor("black");

$graph->legend->SetFrameWeight(1);
$graph->legend->SetColumns(7);
$graph->legend->SetColor('black','black');
$graph->title->SetColor("white"); //title color

$graph->title->SetFont(FF_VERDANA,FS_BOLD,13); 

$graph->title->Set("Weekly sentiments for ".$_SESSION['txtSearch']);

$graph->xaxis->SetColor("white","white"); //x y axis renkler
$graph->yaxis->SetColor("white","white");
//bu sefer işin içinde PubDate var farklı farklı sonuçlar üretilecek hepsi için
$graph->SetBackgroundImage("design_files/black.png",BGIMG_FILLFRAME);

$cnt=0;
if($_SESSION['hashTag']==1)
{
	for($i=7;$i>0;$i--)
	{
		
		$positive=0;
		$negative=0;
		
		$today = date('Y-m-d H:i:s');	
		$dateToday = new DateTime($today);
		$subDate="P0Y0M".($i)."DT0H0M0S";	
		$dateToday->sub(new DateInterval($subDate));
		
		$yesterday=$dateToday->format('Y-m-d 00:00:00');
		$before=$dateToday->format('Y-m-d 23:59:59');
		
		echo "now:".$today;
		echo "yesterday:".$yesterday;
		echo "before:".$before;
		
		$sql="SELECT count(*) As PosCount FROM tweet2hashtags, tweets WHERE Hash='".$_SESSION['txtSearch']."' AND tweet2hashtags.TID=tweets.TID AND tweets.PubDate>='".$yesterday."' AND tweets.PubDate<='".$before."' AND Sentiment='1'";
		$result = mysql_query($sql,$con);
		 if( $row = mysql_fetch_array($result))
    		$positive = $row["PosCount"];
			
			$sql="SELECT count(*) As NegCount FROM tweet2hashtags, tweets WHERE Hash='".$_SESSION['txtSearch']."' AND tweet2hashtags.TID=tweets.TID AND tweets.PubDate>='".$yesterday."' AND tweets.PubDate<='".$before."' AND Sentiment='-1'";
		$result = mysql_query($sql,$con);
		 if( $row = mysql_fetch_array($result))
    		$negative = $row["NegCount"];
		//vertical bar chartını oluştur
		//if($positive+$negative>0)
		//{
			$labels[$cnt]=$dateToday->format('Y-m-d');
			echo "içinde".$cnt.($positive+$negative)."<br>";
	
			$data1[$cnt]=($positive/($positive+$negative))*100;
			$data2[$cnt]=($negative/($positive+$negative))*100;
			
			$cnt++;
		//}
	}
}
else
{
	for($i=7;$i>0;$i--)
	{
		$sql = "SELECT EID FROM entities WHERE MID='".$_SESSION['keywordMid']."'";
		$result = mysql_query($sql, $con) or die(mysql_error());
		while($row = mysql_fetch_array($result))   //aslında döngüye gerek yok sadece 1 tane dönecek ama öbür metodla saçmaladı
		{	
			$eid=$row['EID'];
		}
	
		
		$positive=0;
		$negative=0;
		
		$today = date('Y-m-d H:i:s');	
		$dateToday = new DateTime($today);
		$subDate="P0Y0M".($i)."DT0H0M0S";	
		$dateToday->sub(new DateInterval($subDate));
		
		$yesterday=$dateToday->format('Y-m-d 00:00:00');
		$before=$dateToday->format('Y-m-d 23:59:59');
		
		echo "now:".$today;
		echo "yesterday:".$yesterday;
		echo "before:".$before;
		
		$sql="SELECT count(*) As PosCount FROM tweet2entities, tweets WHERE EID='".$eid."' AND tweet2entities.TID=tweets.TID AND tweets.PubDate>='".$yesterday."' AND tweets.PubDate<='".$before."' AND Sentiment='1'";
		$result = mysql_query($sql,$con);
		 if( $row = mysql_fetch_array($result))
    		$positive = $row["PosCount"];
			
		$sql="SELECT count(*) As NegCount FROM tweet2entities, tweets WHERE EID='".$eid."' AND tweet2entities.TID=tweets.TID AND tweets.PubDate>='".$yesterday."' AND tweets.PubDate<='".$before."' AND Sentiment='-1'";
		$result = mysql_query($sql,$con);
		 if( $row = mysql_fetch_array($result))
    		$negative = $row["NegCount"];
		
		//
	
   
		//
		//vertical bar chartını oluştur
		//if($positive+$negative>0)
		//{
			$labels[$cnt]=$dateToday->format('Y-m-d');
			echo "içinde".$cnt.($positive+$negative)."<br>";
	
			$data1[$cnt]=($positive/($positive+$negative))*100;
			$data2[$cnt]=($negative/($positive+$negative))*100;
			
			$cnt++;
		//}
	}
}


if($cnt>0)
{
	$b1plot = new BarPlot($data1);
	$b2plot = new BarPlot($data2);		
	$b1plot->SetColor("green");
	$b1plot->SetFillColor("green");
	$b1plot->SetLegend("Positive");
	$b2plot->SetColor("red");
	$b2plot->SetFillColor("red");
	$b2plot->SetLegend("Negative");
	$gbbplot = new AccBarPlot(array($b1plot,$b2plot));
	$graph->Add($gbbplot);
	$graph->xaxis->SetTickLabels($labels);
	@unlink("reports/".$_SESSION['userId']."g2.png"); 
	$graph->Stroke("reports/".$_SESSION['userId']."g2.png");
}
else
{
	@unlink("reports/".$_SESSION['userId']."g2.png"); 
}
//1 günden 
//weekly sentiment graph bitti
//horizontal graphları çiz
//önce search edilenin typeını al

//databasede bu tipe ait ama bunun dışındaki entityleri bul 10 tane
//her enetity için
	$_SESSION['relatedMids']="";
	$_SESSION['relatedItemNames']="";
	$_SESSION['relatedItemCount']="";
if($_SESSION['hashTag']!=1)
{
	$sql = "SELECT EID FROM entities WHERE MID='".$_SESSION['keywordMid']."'";
	$result = mysql_query($sql, $con) or die(mysql_error());
	while($row = mysql_fetch_array($result))   //aslında döngüye gerek yok sadece 1 tane dönecek ama öbür metodla saçmaladı
	{	
		$eid=$row['EID'];
	}
	$relatedType=strtolower($_SESSION['keywordType']);
	$sql = 	"SELECT EID2 FROM entityrelations WHERE EID1='".$eid."' LIMIT 5";
	$result = mysql_query($sql, $con) or die(mysql_error());
	$index=0;
	while($row = mysql_fetch_array($result))   //aslında döngüye gerek yok sadece 1 tane dönecek ama öbür metodla saçmaladı
	{	
		$eid=$row['EID2'];
		//şimdi bu entitynin 
		//tipi bununla aynı olan ama eid si aynı olmayanları bul
	
		$sql = 	"SELECT MID,Title FROM entities WHERE EID='".$eid."'";
		$result1 = mysql_query($sql, $con) or die(mysql_error());
	
		
		while($row1 = mysql_fetch_array($result1))   //aslında döngüye gerek yok sadece 1 tane dönecek ama öbür metodla saçmaladı
		{	
			//her biri için grafik çizilecek sentimentlerine bağlı olarak
			$arr=sentimentFromTweets($row1[0]);
			$positive=$arr[0];
			$negative=$arr[1];
			produceHorizontalGraph($positive,$negative,$index);
			$entityNames[$index]=$row1[1];
			$relatedMids[$index]=$row1[0];
			$index=$index+1;
			
		}
		$_SESSION['relatedMids']=$relatedMids;
		$_SESSION['relatedItemNames']=$entityNames;
		$_SESSION['relatedItemCount']=$index;
	}

}


echo $entityNames[0];
echo $entityNames[1];
//

mysql_close($con);

header("location:search.php");

ob_end_flush(); 

?>



